/*
 * Copyright (c) 2007, intarsys consulting GmbH
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * - Neither the name of intarsys nor the names of its contributors may be used
 *   to endorse or promote products derived from this software without specific
 *   prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package de.intarsys.pdf.example.content;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import de.intarsys.pdf.content.common.CSCreator;
import de.intarsys.pdf.example.common.CommonJPodRendererExample;
import de.intarsys.pdf.pd.PDImage;
import de.intarsys.pdf.pd.PDPage;
import de.intarsys.pdf.platform.cwt.image.awt.ImageConverterAwt2Pdf;
import de.intarsys.tools.file.FileTools;

/**
 * Create a document and draw an image at position 100x100 on the page.
 */
public class DrawImage extends CommonJPodRendererExample {

	public static void main(String[] args) {
		DrawImage client = new DrawImage();
		try {
			client.run(args);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public PDPage addPage() {
		// Then create the first page.
		PDPage page = (PDPage) PDPage.META.createNew();
		// add page to the document.
		getDoc().addPageNode(page);
		return page;
	}

	public void draw(PDPage page, File imageFile) throws IOException {
		BufferedImage image = loadImage(imageFile);
		int width = image.getWidth();
		int height = image.getHeight();
		//
		ImageConverterAwt2Pdf converter = new ImageConverterAwt2Pdf(image);
		converter.setPreferJpeg(true);
		PDImage pdImage = converter.getPDImage();
		//
		// open a device to the page content stream
		CSCreator creator = CSCreator.createNew(page);

		creator.saveState();
		creator.transform(width, 0, 0, height, 100, 100);
		creator.doXObject(null, pdImage);
		creator.restoreState();

		// don't forget to flush the content.
		creator.close();
	}

	@SuppressWarnings("rawtypes")
	protected BufferedImage loadImage(File file) throws IOException {
		Iterator i = ImageIO.getImageReadersBySuffix(FileTools
				.getExtension(file));
		ImageReader imgReader = null;
		if (i.hasNext()) {
			imgReader = (ImageReader) i.next();
		} else {
			throw new IOException("No image reader available for file '"
					+ file.getAbsolutePath() + "'");
		}
		ImageInputStream is = null;
		try {
			is = ImageIO.createImageInputStream(file);
			imgReader.setInput(is);
			int count = imgReader.getNumImages(true);
			if (count == 0) {
				return null;
			}
			return imgReader.read(0);
		} finally {
			if (is != null) {
				is.close();
			}
			imgReader.dispose();
		}
	}

	public void run(String[] args) throws Exception {
		if (args.length < 1) {
			usage();
			return;
		}
		try {
			String imageFileName = args[0];
			String outputFileName = args[1];
			create();
			PDPage page = addPage();
			draw(page, new File(imageFileName));
			save(outputFileName);
		} finally {
			close();
		}
	}

	/**
	 * Help the user.
	 */
	public void usage() {
		System.out.println("usage: java.exe " + getClass().getName() //$NON-NLS-1$
				+ " <image-filename> <output-filename>"); //$NON-NLS-1$
	}
}
